package com.ylr.admin.framework.resolver;

import com.ylr.admin.framework.feign.client.YaUserClient;
import com.ylr.base.common.constant.RedisConstant;
import com.ylr.base.common.exception.YlrException;
import com.ylr.base.common.po.user.UserAuthenticationDto;
import com.ylr.base.common.tool.Result;
import com.ylr.base.common.utils.RandomNumUtils;
import com.ylr.redis.framework.service.RedisService;
import com.ylr.redis.framework.service.RedisStringService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-05-12 09:53:44
 * className: YaUserResolver
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class YaUserResolver {

    private static final Logger log = LoggerFactory.getLogger(YaUserResolver.class);

    private final YaUserClient yaUserClient;

    private final RedisStringService redisStringService;

    private final RedisService redisService;

    /**
     * 获取用户认证数据操作
     * @param userId 用户主键
     * @return 用户关联的系统接口数据
     */
    public UserAuthenticationDto getAuthentication(Long userId) {

        String redisKey = RedisConstant.USER_AUTHENTICATION_PREFIX + userId;
        // 1、查询缓存
        UserAuthenticationDto userAuthenticationDto = redisStringService.get(redisKey);
        if (Objects.nonNull(userAuthenticationDto)) {
            // 尝试更新缓存过期时间
            redisService.tryUpdateKeyExpire(redisKey, 900, RandomNumUtils.randomNum(1800, 10));
            return userAuthenticationDto;
        }
        // 2、查询服务
        Result<UserAuthenticationDto> result = yaUserClient.getAuthentication(userId);
        if (result.isFail()) {
            log.warn("调用admin模块，获取用户认证数据失败。message={}", result.getMsg());
            throw new YlrException(result);
        }

        userAuthenticationDto = result.getData();
        // 3、添加缓存
        redisStringService.set(redisKey, userAuthenticationDto, RandomNumUtils.randomNum(1800, 10));

        return userAuthenticationDto;
    }
}
